package com.xiaoma.verbal.service;

import java.util.Date;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.xiaoma.verbal.dao.PrctPracticeDao;
import com.xiaoma.verbal.domain.PrctPractice;

@Service
public class PrctPracticeService {
	private static final Logger LOG = LoggerFactory.getLogger(PrctPracticeService.class);
	@Autowired
	private PrctPracticeDao prctPracticeDao;

	public void increaseTotal(Integer userId) {
		PrctPractice bean = this.findByuserId(userId);
		if (bean != null) {
			bean.setTotal(bean.getTotal() + 1);
			this.prctPracticeDao.update(bean);
		} else {
			bean = new PrctPractice();
			bean.setCreateTime(new Date());
			bean.setUpdateTime(bean.getCreateTime());
			bean.setUserId(userId);
			bean.setTotal(1);
			bean.setCorrectedCount(0);
			this.prctPracticeDao.insert(bean);
		}
	}

	public void increaseCorrected(Integer userId) throws Exception {
		PrctPractice bean = this.findByuserId(userId);
		if (bean != null) {
			bean.setCorrectedCount(bean.getCorrectedCount() + 1);
			bean.setUpdateTime(new Date());
			this.prctPracticeDao.update(bean);
		} else {
			LOG.debug("PrctPractice userId {} missing!", userId);
			throw new Exception("PrctPractice userId {" + userId + "} missing!");
		}
	}

	public PrctPractice findByuserId(Integer userId) {
		PrctPractice bean = new PrctPractice();
		bean.setUserId(userId);
		List<PrctPractice> list = this.prctPracticeDao.findByColumns(bean);
		if (!CollectionUtils.isEmpty(list)) {
			return list.get(0);
		}
		return null;
	}
}
